package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     * 二合一，用户登录也是有游客登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1. 如果参数都有值-则按照正常登录处理
        if (StringUtils.isNotBlank(dto.getPassword())&&StringUtils.isNotBlank(dto.getPhone())){
            //1.1 判断用户是否存在  select * from ap_user where phone=?
            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }

            //1.2 判断密码是否正确
            String loginPwd = dto.getPassword();
            String dbPwd = apUser.getPassword();
            boolean flag = BCrypt.checkpw(loginPwd, dbPwd);
            if (!flag){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.3 判断状态是否正常
            if (apUser.getStatus()){
                return ResponseResult.errorResult(AppHttpCodeEnum.INVALID_STATUS);
            }

            //1.4 生成用户Token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map map = new HashMap<>();
            map.put("token",token);
            map.put("data",apUser);
            return ResponseResult.okResult(map);
        }else {
            //2. 如果参数无值-则按照游客登录处理
            String token = AppJwtUtil.getToken(0L);
            Map hashMap = new HashMap();
            hashMap.put("token",token);
            return ResponseResult.okResult(token);

        }


    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser> findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
